package com.example.androidshixi;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import java.util.ArrayList;
import java.util.List;

public class MyArticlesActivity extends AppCompatActivity {
    private ListView articleListView;
    private List<Article> myArticleList = new ArrayList<>(); // 初始化空列表
    private ArticleViewModel articleViewModel;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_articles); // 只调用一次

        // 初始化视图和ViewModel
        articleListView = findViewById(R.id.article_list_view);
        if (articleListView == null) {
            throw new IllegalStateException("ListView not found in layout. Check activity_my_articles.xml");
        }

        articleViewModel = new ViewModelProvider(this).get(ArticleViewModel.class);
        loadArticles();
    }

    private void loadArticles() {
        // 1. 处理从AddArticleActivity传递的新文章
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("new_article")) {
            Article newArticle = intent.getParcelableExtra("new_article");
            if (newArticle != null) {
                articleViewModel.addArticle(newArticle);
            }
        }

        // 2. 从ViewModel获取所有文章
        List<Article> allArticles = articleViewModel.getArticleList();
        if (allArticles != null) {
            myArticleList.clear();
            myArticleList.addAll(allArticles);
        }

        updateAdapter();
    }

    private void updateAdapter() {
        ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(
                this,
                R.layout.article_item,
                R.id.article_title_text_view,
                myArticleList
        ) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                Article article = getItem(position);
                if (article != null) {
                    TextView titleView = view.findViewById(R.id.article_title_text_view);
                    TextView contentView = view.findViewById(R.id.article_content_text_view);
                    titleView.setText(article.getTitle());
                    contentView.setText(article.getContent());
                }
                return view;
            }
        };
        articleListView.setAdapter(adapter);
    }
}